package com.sita.bike.ui.activity;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.sita.bike.R;
import com.sita.bike.event.TrackSyncedEvent;
import com.sita.bike.persistence.Route;
import com.sita.bike.persistence.RouteData;
import com.sita.bike.ui.fragments.DayGatherFragment;
import com.sita.bike.ui.fragments.MapFragment;
import com.sita.bike.ui.fragments.MonthGatherFragment;
import com.sita.bike.ui.fragments.YearGatherFragment;
import com.sita.bike.utils.LogUtils;
import com.sita.bike.utils.PersistUtils;
import com.sita.bike.utils.TracksInfoUtils;
import com.sita.tboard.ActivityBase;
import com.sita.tboard.ui.event.DateSelectedChangeEvent;
import com.sita.tboard.ui.fragment.RpmLineChartFragment;
import com.sita.tboard.ui.fragment.SpeedLineChartFragment;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;

public class DataAnalysisActivity extends ActivityBase implements View.OnClickListener {

    private final String TAG = DataAnalysisActivity.class.getSimpleName();
    private static DataAnalysisActivity mInstance;
    @Bind(R.id.year_gather)
    public TextView tv_year;
    @Bind(R.id.month_gather)
    public TextView tv_month;
    @Bind(R.id.day_gather)
    public TextView tv_day;
    @Bind(R.id.back)
    public ImageView img_back;
    @Bind(R.id.tv_max_speed)
    public TextView maxSpeed;
    @Bind(R.id.tv_avg_speed)
    public TextView averageSpeed;
    @Bind(R.id.tv_total_distance)
    public TextView totalDistance;
    @Bind(R.id.tv_total_time)
    public TextView totalTime;
    @Bind(R.id.scrollview_data)
    public ScrollView scrollViewData;
    //所有速度点的集合
    private ArrayList<Float> speedValues;
    private List<Route> dayRoutes;
    private float maxSpeedNum;
    private float totalSpeedNum;
    private float averageSpeedNum;
    private int year;
    private int month;
    private int day;
    private ProgressDialog mProgressDialog;

    public static int getSystemYear() {
        Calendar calendar = Calendar.getInstance();
        return calendar.get(Calendar.YEAR);
    }

    public static int getSystemMonth() {
        Calendar calendar = Calendar.getInstance();
        return calendar.get(Calendar.MONTH);
    }

    public static int getSystemDay() {
        Calendar calendar = Calendar.getInstance();
        return calendar.get(Calendar.DAY_OF_MONTH);
    }

    public static DataAnalysisActivity getInstance() {
        return mInstance;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_data_analysis);
        mInstance = this;
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
//        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//        setSupportActionBar(toolbar);
        addFragment();
        initView();
        initVar();

        mProgressDialog = new ProgressDialog(this);
        String str = getResources().getString(R.string.is_sync_track_list);
        mProgressDialog.setMessage(str);
        mProgressDialog.setCanceledOnTouchOutside(false);
        mProgressDialog.show();
        TracksInfoUtils.syncTracks(new TracksInfoUtils.SyncListener() {
            @Override
            public void Success(boolean hasSynced) {
                if (hasSynced) {
                    return;
                }
                if (getTracksData()) {
                    scrollViewData.setVisibility(View.VISIBLE);
                    initSpeedChart();
                    initRunChart();
                    initMap();
                } else {
                    scrollViewData.setVisibility(View.GONE);
                }
                mProgressDialog.dismiss();
            }

            @Override
            public void Fail() {
            }
        });


    }

    public void onEventMainThread(TrackSyncedEvent event) {
        LogUtils.d(TAG, "TrackSyncedEvent：");

        if (getTracksData()) {
            scrollViewData.setVisibility(View.VISIBLE);
            initSpeedChart();
            initRunChart();
            initMap();
        } else {
            scrollViewData.setVisibility(View.GONE);
        }

        mProgressDialog.dismiss();
    }

    public void addFragment() {
        tv_day.setBackgroundColor(getResources().getColor(R.color.white));
        FragmentTransaction ftx = getSupportFragmentManager().beginTransaction();
        ftx.replace(R.id.data_fragment, DayGatherFragment.getInstance());
        ftx.addToBackStack(null);
        ftx.commit();
    }

    public void initView() {
        tv_day.setOnClickListener(this);
        tv_month.setOnClickListener(this);
        tv_year.setOnClickListener(this);
        tv_day.setSelected(true);
    }

    public void initSpeedChart() {
        //传入当前日期
        FragmentTransaction ftx = getSupportFragmentManager().beginTransaction();
        SpeedLineChartFragment speedLineChartFragment = SpeedLineChartFragment.getInstance(speedValues, maxSpeedNum);
        ftx.replace(R.id.seedChart, speedLineChartFragment);
        ftx.addToBackStack(null);
        ftx.commit();
    }

    public void initRunChart() {
        FragmentTransaction ftx = getSupportFragmentManager().beginTransaction();
        ftx.replace(R.id.runChart, RpmLineChartFragment.getInstance());
        ftx.addToBackStack(null);
        ftx.commit();
    }

    public void initMap() {
        FragmentTransaction ftx = getSupportFragmentManager().beginTransaction();
        ftx.replace(R.id.mapfragment, MapFragment.getInstance(dayRoutes));
        ftx.addToBackStack(null);
        ftx.commit();
    }

    @Override
    public void onClick(View v) {
        FragmentTransaction ftx = getSupportFragmentManager().beginTransaction();
        switch (v.getId()) {
            case R.id.year_gather:
                tv_year.setBackgroundColor(getResources().getColor(R.color.white));
                tv_month.setBackgroundColor(getResources().getColor(R.color.nocolor));
                tv_day.setBackgroundColor(getResources().getColor(R.color.nocolor));
                ftx.replace(R.id.data_fragment, YearGatherFragment.getInstance());
                ftx.addToBackStack(null);
                ftx.commit();
                break;
            case R.id.month_gather:
                tv_year.setBackgroundColor(getResources().getColor(R.color.nocolor));
                tv_month.setBackgroundColor(getResources().getColor(R.color.white));
                tv_day.setBackgroundColor(getResources().getColor(R.color.nocolor));
                ftx.replace(R.id.data_fragment, MonthGatherFragment.getInstance());
                ftx.addToBackStack(null);
                ftx.commit();
                break;
            case R.id.day_gather:
                tv_year.setBackgroundColor(getResources().getColor(R.color.nocolor));
                tv_month.setBackgroundColor(getResources().getColor(R.color.nocolor));
                tv_day.setBackgroundColor(getResources().getColor(R.color.white));
                ftx.replace(R.id.data_fragment, DayGatherFragment.getInstance());
                ftx.addToBackStack(null);
                ftx.commit();
                break;
        }

    }

    @OnClick(R.id.back)
    public void dataBack() {
        finish();
    }

    //
    private void initVar() {
        maxSpeedNum = 0;
        totalSpeedNum = 0;
        averageSpeedNum = 0;
    }

    //分析数据
    public boolean getTracksData() {
        int selectYear = getCurrentYear();
        int selectMonth = getCurrentMonth() - 1;
        int selectDay = getCurrentDay();
        long startTime = getTime(selectYear, selectMonth, selectDay);
        long endTime = getTime(selectYear, selectMonth, selectDay + 1);

        //一天中所有的路线
        dayRoutes = new ArrayList<>();
        dayRoutes = PersistUtils.getTimeSelectRoutes(startTime, endTime);
        //从所有路线中读到所有的点，循环读路线，把所有点的速度加到list中
        speedValues = new ArrayList<>();
        Iterator iterator = dayRoutes.iterator();
        while (iterator.hasNext()) {
            //单条路线
            Route track = (Route) iterator.next();
            long trackId = track.getId();
            //获得单条路线中的gps信息点集合
            List<RouteData> routeDataList = PersistUtils.getRouteDataList(trackId);
            for (int j = 0; j < routeDataList.size(); ++j) {
                double spd = routeDataList.get(j).getSpeed() * 3.6;

                speedValues.add((float) spd);
                //算出速度最大值和平均值
                if (maxSpeedNum < (float) spd) {
                    maxSpeedNum = (float) spd;
                }
                totalSpeedNum = totalSpeedNum + (float) spd;
            }
        }
        averageSpeedNum = totalSpeedNum / speedValues.size();
        maxSpeed.setText(formatSpeed(maxSpeedNum));
        averageSpeed.setText(formatSpeed(averageSpeedNum));
        totalDistance.setText(TracksInfoUtils.getTracksDistance(dayRoutes));
        totalTime.setText(TracksInfoUtils.getTracksTime(dayRoutes));
        return (dayRoutes.size() == 0 ? false : true);
    }

    private long getTime(int year, int month, int day) {
        Date date = new Date();
        date.setYear(year - 1900);
        date.setMonth(month);
        date.setDate(day);
        date.setHours(0);
        date.setMinutes(0);
        date.setSeconds(0);
        return date.getTime();
    }

    private String formatSpeed(float speed) {
        String distance_result = "0";
        DecimalFormat decimalFormat;
        if (speed < 10) {
            decimalFormat = new DecimalFormat("0.00");
            distance_result = decimalFormat.format(speed);
        } else if (speed >= 10 && speed < 100) {
            decimalFormat = new DecimalFormat("0.0");
            distance_result = decimalFormat.format(speed);
        } else if (speed >= 100) {
            decimalFormat = new DecimalFormat("0");
            distance_result = decimalFormat.format(speed);
        }
        return distance_result;
    }

    public int getCurrentYear() {
        if (year == 0) {
            year = getSystemYear();
        }
        return year;
    }

    public void setCurrentYear(int year) {
        this.year = year;
    }

    public int getCurrentMonth() {
        if (month == 0) {
            month = getSystemMonth() + 1;
        }
        return month;
    }

    public void setCurrentMonth(int month) {
        this.month = month;
    }

    public int getCurrentDay() {
        if (day == 0) {
            day = getSystemDay();
        }
        return day;

    }

    public void setCurrentDay(int day) {
        this.day = day;
    }

    public void onEventMainThread(DateSelectedChangeEvent event) {
        //当用户重新选择了其他日期，重新获取数据，更新页面
            initVar();
        if (getTracksData()) {
            scrollViewData.setVisibility(View.VISIBLE);
            initSpeedChart();
            initRunChart();
            initMap();
        } else {
            scrollViewData.setVisibility(View.GONE);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
